package com.snu.liwei.lyl_api.controller;

import com.snu.liwei.lyl_api.config.StaticConfig;
import com.snu.liwei.lyl_api.entity.User;
import com.snu.liwei.lyl_api.service.UserService;
import com.snu.liwei.lyl_api.tools.UMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//this annotation can transform an object into json and then transmit json to front-end or just send a string if you only return a string.
@RestController
//this annotation can allow a special client server to cross domain which is banned by all browsers.
@CrossOrigin(origins = {"http://192.168.31.215:3000","http://127.0.0.1:3000"})
@RequestMapping(value = "User",produces = "application/json;charset=UTF-8")
public class LoginController {
    //动手前先看注释！！！！！
    //for threads safety,please do not define any instance variable in a controller
    //there are some articles can help you understand how spring mvc keep thread safety.
    //https://blog.csdn.net/lin252552/article/details/82589604
    //https://zhuanlan.zhihu.com/p/377433109
    //https://www.cnblogs.com/qishuai/p/4500231.html
    //https://www.cnblogs.com/tonyliang/p/4202953.html

    @Autowired
    UserService userService;
    @RequestMapping("Login")
    // if use '@RequestBody',you can only send post requirements from client.
    //if you send get requirements ,you need use '@RequestParam' to accept params.
    public UMsg login(@RequestBody User loginUser) {
        System.out.println("登录接口");
        //Map<String, Object> result = new HashMap<>();
        User userInDb=userService.getUser(loginUser);
        System.out.println(userInDb);
        if (userInDb!=null)
        {
            String access_token= UUID.randomUUID()+"";
            userInDb.setToken(access_token);

            //放入缓存数据库中
            StaticConfig.SimRedis.put(access_token,userInDb);

            userService.updateToken(userInDb);
            //result.put("user",userInDb);
            return UMsg.ok(userInDb);
        }
        else {
            //System.out.println("登录失败:"+loginUser.toString());
            return UMsg.failed();
        }
    }

    @RequestMapping("NotLogin")
    public String NotLogin()
    {
        System.out.println("未登录");
        return "Not Login";
    }


}
